package org.csu.canteen.entity;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import org.csu.canteen.service.ItemService;

import java.math.BigDecimal;

@Data
@TableName("cartitem")
public class CartItem {
    @TableId(value = "username")
    private String username;

    @TableField(value = "itemid")
    private String itemId;

    @TableField(value = "number")
    private Integer number=1;

    @TableField(exist = false)
    private Item item;

    @TableField(exist = false)
    private Boolean inStock;

    @TableField(exist = false)
    private BigDecimal total;

    public void initItem(ItemService itemService) {
        this.item = itemService.getItem(this.itemId);
        calculateTotal(); // 重新计算总价
    }

    public void setItem(Item item) {
        this.item = item;
        calculateTotal();
    }

    public void setNumber(int number) {
        this.number = number;
        calculateTotal();
    }

    private void calculateTotal() {
        if (item != null && item.getListPrice() != null) {
            total = item.getListPrice().multiply(new BigDecimal(number));
        } else {
            total = null;
        }
    }

    public void incrementQuantity() {
        number++;
        calculateTotal();
    }

    public int getQuantity() {
        return number;
    }

    public boolean isInStock() {
        return inStock;
    }
}